package com.pms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.pms.dao.UserDao.UserRowMapper;
import com.pms.entity.Recoder;
import com.pms.entity.User;
import com.pms.util.DBHelp;
import com.pms.util.Page;
import com.pms.util.RowMapper;

public class RecorderDao {
	
	private DBHelp<Recoder> db=new DBHelp<Recoder>();
	public void save(Recoder recoder){
		String sql="INSERT INTO t_recoder(recoderid,`desc`,createtime,userid,contactid) VALUES(?,?,?,?,?)";
		db.executeSQL(sql,recoder.getRecoderId(),recoder.getDesc(),recoder.getCreateTime(),recoder.getUserId(),recoder.getContactId());
	}
	
	public Long getCount(){
		String sql="select count(*) from t_recoder";
		 return (Long)db.executeQueryForFunction(sql);
		
	}
	
	public Page<Recoder> findByUserIdAndContactId(String contactId,Page<Recoder> page){
		StringBuilder sql=new StringBuilder();
		sql.append("SELECT tr.recoderid,tr.desc,tr.createtime,tr.userid,tr.contactid,tu.userid,tu.username,tu.password,tu.nickname,tu.picture FROM t_recoder AS tr ");
		sql.append("LEFT JOIN t_user AS tu ON tr.userid=tu.userid ");
		sql.append("WHERE contactid=?  ORDER BY createtime DESC limit ?,?");
		List<Recoder> list= db.executeQueryForList(sql.toString(), new RecoderRowMapper(),contactId,page.getOffSet(),page.getPageSize());
		page.setResult(list);
		return page;
	
	}
	
	
	public void delRecoder(String contactId){
		String sql="delete from t_recoder where contactid=?";
		db.executeSQL(sql, contactId);
	}
	
	
	public class RecoderRowMapper implements RowMapper<Recoder>{

		
		public Recoder mapRow(ResultSet rs) throws SQLException {
			User user=new User();
			user.setUserId(rs.getString("userId"));
			user.setUserName(rs.getString("userName"));
			user.setPassword(rs.getString("password"));
			user.setNickName(rs.getString("nickName"));
			user.setPicture(rs.getString("picture"));
			
			
			Recoder recoder=new Recoder();
			recoder.setUser(user);
			recoder.setRecoderId(rs.getString("recoderId"));
			recoder.setDesc(rs.getString("desc"));
			recoder.setCreateTime(rs.getString("createTime"));
			recoder.setUserId(rs.getString("userId"));
			recoder.setContactId(rs.getString("contactId"));
			return recoder;
		}
		
	}
}
